package john.walker.log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 30san
 *
 */
public class FileLogger extends AbstractLogger {

	public static String logFileName = "dbtrace.log";

	private static SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");

	private RandomAccessFile raf ;

	public FileLogger () {
		String rootPath = System.getProperty("catalina.home");
		if(rootPath == null || rootPath.isEmpty()) {
			rootPath = System.getProperty("user.dir");
		}
		rootPath = rootPath + File.separator + "logs";
		if(!new File(rootPath).exists()) {
			new File(rootPath).mkdirs();
		}

		File file = new File(rootPath + File.separator + logFileName);
		if(file.exists()) { // 如果文件存在，则重命名文件，且文件大小不为0
			if(file.length() > 0) {
				file.renameTo(new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().length()-4) + "_" + format.format(new Date()) + ".log"));
			}
		} else {
			file.getParentFile().mkdirs();
		}
		System.out.println("日志文件路径： " + file.getAbsolutePath());
		try {
			this.raf = new RandomAccessFile(file, "rw");
			if(raf.length() > 0) {
				raf.seek(raf.length());
			}
			Runtime.getRuntime().addShutdownHook(new Thread(){

				@Override
				public void run() {
					FileLogger.this.destroy();
				}
			});
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}


	public void setLogPath(String absolutePath) {
		if(absolutePath == null || absolutePath.trim().isEmpty()) {
			throw new RuntimeException("the path can not be empty!");
		}
		File file = new File(absolutePath);
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		if(raf != null) {
			try {
				raf.close();
				raf = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			raf = new RandomAccessFile(file, "rw");
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}


	@Override
	public void debug(String msg) {
		if(this.raf != null) {
			try {
				raf.write(msg.getBytes());
				raf.write("\r\n".getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	@Override
	public void info(String msg) {
		debug(msg);
	}


	@Override
	public void warn(String msg) {
		debug(msg);
	}


	@Override
	public void error(String msg) {
		debug(msg);
	}


	@Override
	public void fatal(String msg) {
		debug(msg);
	}


	@Override
	public void newLine() {
		if(this.raf != null) {
			try {
				raf.seek(raf.length());
				raf.write("\r\n".getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void destroy(){
		if(raf != null) {
			try {
				raf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
